package com.dorso.controller;

import com.dorso.entity.Product;
import com.dorso.exception.ProductAdminException;
import com.dorso.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    ProductService productService;
    //根据id查询产品
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable long id){
        Product product=productService.getById(id);
        if(product==null){
            return ResponseEntity.noContent().build();
        }else {
            return ResponseEntity.ok(product);
        }
    }
    //查询供应商
    @GetMapping("")
    public IPage<Product> findProduct(String name,
                                      Double price,
                                      Integer num,
                                      String supplierName,
                                     @RequestParam(defaultValue = "0")Integer pageNum,
                                      @RequestParam(defaultValue = "10")Integer pageSize){
        Map<String,Object> condition=new HashMap<>();
        if(name!=null) {
            condition.put("name","%"+name+"%");
        }
        if(price!=null) {
            condition.put("price",price);
        }
        if(num!=null) {
            condition.put("num",num);
        }
        if(supplierName!=null) {
            condition.put("supplierName",supplierName);
        }
        return productService.findProduct(condition, pageNum,pageSize);
    }
    @PostMapping("")
    //添加商品
    public Product addProduct(@RequestBody Product product)throws ProductAdminException {
        return productService.addProduct(product);
    }
    //修改商品信息
    @PutMapping("/{id}")
    public void updateProduct(@PathVariable long id,@RequestBody Product product) throws ProductAdminException{
        productService.updateProduct(id,product);
    }
    //删除商品
    @DeleteMapping("/{id}")
//    public ResponseEntity<Void> deleteProduct(@PathVariable long id){
//        productService.deleteProduct(id);
//        return ResponseEntity.ok().build();
//    }
    public void deleteProduct(@PathVariable long id){
        productService.removeById(id);
    }
}
